package ch02sl.sz.sz2;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

public class Dom4JParse {
    public static void main(String[] args) {
        // 创建SAXReader对象
        SAXReader reader = new SAXReader();
        try {
            // 读取XML文件，生成Document对象
            Document document = reader.read(new File("src/test/java/ch02sl/sz/PhoneInfo.xml"));
            // 获取根节点
            Element root = document.getRootElement();
            // 遍历Brand节点
            for (Iterator<Element> it = root.elementIterator("Brand"); it.hasNext(); ) {
                Element brand = it.next();
                // 获取Brand的属性值
                String brandName = brand.attributeValue("name");

                // 如果品牌名称为"三星"，则修改为"SAMSUNG"
                if ("三星".equals(brandName)) {
                    brand.setAttributeValue("name", "SAMSUNG");
                }
                // 遍历Type节点
                for (Iterator<Element> typeIt = brand.elementIterator("Type"); typeIt.hasNext(); ) {
                    Element type = typeIt.next();
                    // 获取Type的属性值
                    String typeName = type.attributeValue("name");
                    // 输出品牌和型号
                    System.out.println("手机：" + brandName + typeName);
                }
            }
            Iterator<Element> it1 = root.elementIterator("Brand");
            Element brand1 = it1.next();
            Element name = brand1.element("Brand");
            name.addAttribute("name", "三星");
            // 删除Brand节点中品牌名为"SAMSUNG"的节点
            for (Iterator<Element> it = root.elementIterator("Brand"); it.hasNext(); ) {
                Element brand = it.next();
                if ("SAMSUNG".equals(brand.attributeValue("name"))) {
                    root.remove(brand);
                }
            }
            // 保存修改后的XML文件
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            try {
                XMLWriter writer = new XMLWriter(new FileWriter("src/test/java/ch02sl/sz/PhoneInfo.xml"), format);
                writer.write(document);
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
}